package indi.kider.server.sms.service;

import com.google.gson.Gson;
import indi.kider.common.constant.LeaseBusStateCons;
import indi.kider.common.constant.SmsTemplateCons;
import indi.kider.common.constant.StatusCons;
import indi.kider.common.model.apabus.Rent;
import indi.kider.common.model.employee.Tenant;
import indi.kider.common.model.sms.Sms;
import indi.kider.common.model.woniubus.LeaseBusQuery;
import indi.kider.common.model.woniubus.TenantInHouse;
import indi.kider.server.sms.mapper.SmsMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import pers.vankid.common.constant.HttpCode;
import pers.vankid.common.model.base.CommonResponse;

import java.util.*;

/**
 * Created by shixj on 2018/6/7.
 */
@SuppressWarnings("all")
@Service
@Slf4j
public class SmsServiceImpl implements SmsService {
    @Autowired
    private BillQueryService billQueryService;
    @Autowired
    private SmsMapper        smsMapper;


    /**
     * 消息
     * 获取消息列表
     *
     * @return
     */
    @Override
    @Deprecated
    public List<Sms> getAllSmsList() {
        List<Sms> smsList = new ArrayList<>();
        smsList.addAll(getOverdueWaterBillList());
        smsList.addAll(getOverduePowerBillList());
        smsList.addAll(getOverdueNetBillList());
        smsList.addAll(getOverdueEstateBillList());
        smsList.addAll(getOverdueRentalBillList());
        smsList.addAll(getDueRentalBillList());
        smsList.addAll(getDueRentList());
        return smsList;
    }

    /**
     * 消息
     * 获取超期未支付账单列表 水费
     *
     * @return
     */
    @Override
    public List<Sms> getOverdueWaterBillList() {
        List<Sms> smsList = new ArrayList<>();
        billQueryService.getOverdueWaterBillList().stream().forEach(v -> smsList.addAll(v.build()));
        try {
            sendSms(smsList);
        } catch (Exception e) {

        }
        return smsList;
    }

    /**
     * 获取超期未支付账单列表 电费
     *
     * @return
     */
    @Override
    public List<Sms> getOverduePowerBillList() {
        List<Sms> smsList = new ArrayList<>();
        billQueryService.getOverduePowerBillList().stream().forEach(v -> smsList.addAll(v.build()));
        try {
            sendSms(smsList);
        } catch (Exception e) {

        }
        return smsList;
    }

    /**
     * 消息
     * 获取超期未支付账单列表 物业
     *
     * @return
     */
    @Override
    public List<Sms> getOverdueEstateBillList() {
        List<Sms> smsList = new ArrayList<>();
        billQueryService.getOverdueEstateBillList().stream().forEach(v -> smsList.addAll(v.build()));
        try {
            sendSms(smsList);
        } catch (Exception e) {

        }
        return smsList;
    }

    /**
     * 消息
     * 获取超期未支付账单列表 网费
     *
     * @return
     */
    @Override
    public List<Sms> getOverdueNetBillList() {
        List<Sms> smsList = new ArrayList<>();
        billQueryService.getOverdueNetBillList().stream().forEach(v -> smsList.addAll(v.build()));
        try {
            sendSms(smsList);
        } catch (Exception e) {

        }
        return smsList;
    }

    /**
     * 消息
     * 获取超期未支付账单列表 房租
     *
     * @return
     */
    @Override
    public List<Sms> getOverdueRentalBillList() {
        List<Sms> smsList = new ArrayList<>();
        billQueryService.getOverdueRentalBillList().stream().forEach(v -> smsList.addAll(v.build()));
        try {
            sendSms(smsList);
        } catch (Exception e) {

        }
        return smsList;
    }

    /**
     * 消息
     * 获取即将到期的房租
     *
     * @return
     */
    @Override
    public List<Sms> getDueRentalBillList() {
        List<Sms> smsList = new ArrayList<>();
        billQueryService.getDueRentalBillList().stream().forEach(v -> smsList.addAll(v.build()));
        try {
            sendSms(smsList);
        } catch (Exception e) {

        }
        return smsList;
    }

    /**
     * 消息
     * 获取租期即将到期的
     *
     * @return
     */
    @Override
    public List<Sms> getDueRentList() {
        List<Sms> smsList = new ArrayList<>();
        billQueryService.getDueRentList().stream().forEach(v -> smsList.addAll(v.build()));
        try {
            sendSms(smsList);
        } catch (Exception e) {

        }
        return smsList;
    }

    /**
     * 员工入住提醒(企业管理人员)===========实时发送=========>
     *
     * @param tenantInHouse tenantName pohne
     * @throws Exception
     */
    public CommonResponse tenantSms(TenantInHouse tenantInHouse) throws Exception {
        List<Sms>           smsList = new ArrayList<>();
        Map<String, String> map     = new HashMap<>();
        map.put("companyName", tenantInHouse.getTenantName());
        Sms sms = buildSms(tenantInHouse.getPhone(), map, SmsTemplateCons.TENANT_SMS);
        smsList.add(sms);
        sendSms(smsList);
        return CommonResponse.buildUpdateSuccessResponse("发送成功!", null);
    }

    /**
     * 成功入住提醒===========实时发送=========>
     *
     * @param tenantInHouse houseNum pohne
     * @return
     * @throws Exception
     */
    public CommonResponse tenantSuccessSms(TenantInHouse tenantInHouse) throws Exception {
        List<Sms>           smsList = new ArrayList<>();
        Map<String, String> map     = new HashMap<>();
        map.put("houseNum", tenantInHouse.getHouseNum());
        Sms sms = buildSms(tenantInHouse.getPhone(), map, SmsTemplateCons.TENANT_CHECKIN_SMS);
        smsList.add(sms);
        sendSms(smsList);
        return CommonResponse.buildUpdateSuccessResponse("发送成功!", null);
    }


    /**
     * 失败入住提醒===========实时发送=========>
     *
     * @param tenantInHouse
     * @return
     * @throws Exception
     */
    public CommonResponse tenantFailSms(TenantInHouse tenantInHouse) throws Exception {
        List<Sms>           smsList = new ArrayList<>();
        Map<String, String> map     = new HashMap<>();
        map.put("name1", tenantInHouse.getPartName());
        map.put("name2", tenantInHouse.getPartPhone());
        Sms sms = buildSms(tenantInHouse.getPhone(), map, SmsTemplateCons.TENANT_CHECKNOTIN_SMS);
        smsList.add(sms);
        sendSms(smsList);
        return CommonResponse.buildUpdateSuccessResponse("发送成功!", null);
    }

    /**
     * 退房换房已审核通知===========实时发送=========>
     *
     * @param tenantInHouse
     * @return
     * @throws Exception
     */
    public CommonResponse shSuccessSms(LeaseBusQuery leaseBus) throws Exception {
        List<Sms>           smsList = new ArrayList<>();
        Map<String, String> map     = new HashMap<>();
        map.put("tenantName", leaseBus.getTenantName());
        if(leaseBus.getBusType() == 1){
            Sms sms = buildSms(leaseBus.getTenantTel(), map, SmsTemplateCons.OUTHOUSE_SMS);
            smsList.add(sms);
        }else if(leaseBus.getBusType() == 2){
            Sms sms = buildSms(leaseBus.getTenantTel(), map, SmsTemplateCons.CHANGEHOUSE_SMS);
            smsList.add(sms);
        }
        sendSms(smsList);
        return CommonResponse.buildUpdateSuccessResponse("发送成功!", null);
    }
    /**
     * 重置锁密码短信
     *
     * @param tenant
     * @return
     * @throws Exception
     */
    public CommonResponse resetLockpwdSms(Tenant tenant) throws Exception {
        List<Sms>           smsList = new ArrayList<>();
        Map<String, String> map     = new HashMap<>();
        map.put("tenantName", tenant.getName());
        map.put("pwd", tenant.getPwd());
        Sms sms = buildSms(tenant.getPhone(), map, SmsTemplateCons.LOCKPWD_SMS);
        smsList.add(sms);
        sendSms(smsList);
        return CommonResponse.buildUpdateSuccessResponse("发送成功!", null);
    }
//    @Override
//    public CommonResponse sendStableSms() throws Exception {
//        String ps = "13771128996-" +
//                "15239401429-" +
//                "13107716902-" +
//                "18888775493-" +
//                "18268102907-" +
//                "18267140476-" +
//                "18355608620-" +
//                "15268176363-" +
//                "18110220816-" +
//                "15560001203-" +
//                "15962205676-" +
//                "18717804580-" +
//                "17306426131-" +
//                "15755196771-" +
//                "15829202301-" +
//                "15968148627-" +
//                "15968170663-" +
//                "13968663599-" +
//                "18276726039-" +
//                "15700072052-" +
//                "15967308795-" +
//                "13921152014-" +
//                "18261569915-" +
//                "13961754533-" +
//                "15988025452-" +
//                "13516727897-" +
//                "13587125209-" +
//                "15155926630-" +
//                "18761477605-" +
//                "15179005854-" +
//                "17858851674-" +
//                "15868332341-" +
//                "13136196057-" +
//                "18225918358-" +
//                "13653945319-" +
//                "13924630677-" +
//                "13567119276-" +
//                "13282983769-" +
//                "18258878361-" +
//                "15088634048-" +
//                "15397054263-" +
//                "15958109342-" +
//                "13588771146-" +
//                "18067935810-" +
//                "18857194283-" +
//                "18268100117-" +
//                "18868421335-" +
//                "18838502437-" +
//                "15656036681-" +
//                "13937608476-" +
//                "18260228415-" +
//                "17585476452-" +
//                "15505508290-" +
//                "15606714019-" +
//                "18009681008-" +
//                "17379268912-" +
//                "17681894795-" +
//                "15527101711-" +
//                "17857992625-" +
//                "17713896228-" +
//                "13967191413-" +
//                "17769866553-" +
//                "17855861571-" +
//                "18668043287-" +
//                "18329199516-" +
//                "18626859462-" +
//                "15168429625-" +
//                "13116367202-" +
//                "18368833340-" +
//                "18214963157-" +
//                "13250811170-" +
//                "13588417025-" +
//                "13157101362-" +
//                "18767951290-" +
//                "15578370434-" +
//                "15268189943-" +
//                "13766492140-" +
//                "15026424446-" +
//                "15355258815-" +
//                "13329086818-" +
//                "18555081071-" +
//                "18107929139-" +
//                "15679191651-" +
//                "17703870713-" +
//                "13672100532-" +
//                "13129239213-" +
//                "13151768104-" +
//                "17746805253-" +
//                "17826869170-" +
//                "15255127441-" +
//                "18667947003-" +
//                "15825519563-" +
//                "16637697940-" +
//                "13867141990-" +
//                "18790130780-" +
//                "15356518590-" +
//                "15967417362-" +
//                "13858477947-" +
//                "15215972631-" +
//                "15879068922-" +
//                "18357681965-" +
//                "17826890331-" +
//                "17537645020-" +
//                "19917908520-" +
//                "13388459313-" +
//                "13735600625-" +
//                "18708319175-" +
//                "15381132933-" +
//                "18658155883-" +
//                "13698430124-" +
//                "15270341391-" +
//                "13003026133-" +
//                "15067107725-" +
//                "13605857895-" +
//                "18671138871-" +
//                "18305507922-" +
//                "18757157089-" +
//                "17637617985-" +
//                "18368880354-" +
//                "13362107756-" +
//                "13645819730-" +
//                "18193500142-" +
//                "13136199715-" +
//                "17376581827-" +
//                "17758641778-" +
//                "18506571267-" +
//                "15258869722-" +
//                "15990012561-" +
//                "18655988901-" +
//                "17516087530-" +
//                "18955848555-" +
//                "16657043263-" +
//                "15858898953-" +
//                "15158123425-" +
//                "13022335782-" +
//                "17681895216-" +
//                "15868185448-" +
//                "18357194697-" +
//                "18338559053-" +
//                "18939295739-" +
//                "18790178232-" +
//                "18267172473-" +
//                "13758125659";
//        String[] tms = ps.split("-");
//        for (String t: tms){
//            log.info("【电话号码{}】",t);
//            List<Sms> smsList = new ArrayList<>();
//            Map<String, String> map     = new HashMap<>();
//            map.put("currmonth", "九");
//            map.put("month", "10");
//            map.put("day", "12");
//            Sms sms = buildSms(t, map, SmsTemplateCons.PAYMENT_NOTICE_SMS);
//            smsList.add(sms);
//            sendSms(smsList);
//        }
//
//        return CommonResponse.buildUpdateSuccessResponse("发送成功!", null);
//    }

    /**
     * 组装SMS
     *
     * @param Phones
     * @param map
     * @param templateCode
     * @return
     */
    public Sms buildSms(String Phones, Map<String, String> map, String templateCode) {
        Sms sms = new Sms();
        sms.setPhones(Phones);
        sms.setCreateTime(new Date());
        sms.setTemplateCode(templateCode);
        sms.setTemplateContext(SmsTemplateCons.MAP.get(templateCode));
        sms.setSmsContext(new Gson().toJson(map));
        return sms;
    }

    /**
     * 调用短信服务，处理发送反馈
     *
     * @param smsList
     */
    @Value("${sms.url}")
    private String url;

    private void sendSms(List<Sms> smsList) throws Exception {
        smsList.stream().forEach(sms -> {
            try {
                RestTemplate restTemplate = new RestTemplate();
                HttpHeaders  headers      = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
                MultiValueMap<String, String> p = new LinkedMultiValueMap<>();
                p.add("phones", sms.getPhones());
                p.add("type", sms.getType());
                p.add("signType", sms.getSignType());
                p.add("smsContext", sms.getSmsContext());
                p.add("templateCode", sms.getTemplateCode());
                HttpEntity<MultiValueMap<String, String>> entity         = new HttpEntity<MultiValueMap<String, String>>(p, headers);
                ResponseEntity<String>                    responseEntity = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
                CommonResponse                            response       = new Gson().fromJson(responseEntity.getBody(), CommonResponse.class);
                if (response.getStatus().equals(HttpCode.SUCCESS_GET))
                    sms.setState(StatusCons.VALID);
                else
                    sms.setState(StatusCons.HISTORY);
                sms.setResContext(responseEntity.getBody());
            } catch (Exception e) {
                sms.setState(StatusCons.HISTORY);
                sms.setResContext(new Gson().toJson(CommonResponse.buildBadRequestResponse("调用发送服务失败！")));

                e.printStackTrace();
            } finally {
                smsMapper.insert(sms);
            }
        });

    }
}
